<template>
  <div class="webchatFormBox box_height">
    <div class="tool">
      <div style="float: left">
        <span class="main-color" @click='addFormData'><i class="el-icon-plus"></i><span>新建表单（最多10个）</span></span>
        <!-- <el-input
          style="width: 300px"
          size="mini"
          placeholder="请输入表单名称进行查询"
          @input="handlerClick"
          v-model.trim="query">
          <i class="el-input__icon el-icon-search" slot="suffix" @click="handlerClick"></i>
        </el-input> -->
      </div>
    </div>
    <div class="table-wapper">
      <el-table :data="tableData" size="mini" stripe style="width: 100%">
        <el-table-column label="表单名称" prop='sessionForm.formName'></el-table-column>
        <el-table-column label="描述" prop='sessionForm.description'></el-table-column>
        <el-table-column label="操作" width='150'>
          <template slot-scope="scope">
            <div>
              <el-button @click="editForm(scope.row, scope.$index)" type="text" size="small" class = 'modify'>编辑</el-button>
              <el-button type="text" size="small" class="del" @click = 'delForm(scope.row)'>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" title="编辑表单" :visible.sync="showAddDialog" width="60%">
      <el-form :model="ruleForm.sessionForm" ref="ruleForm" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="表单名称" prop="formName">
          <el-input size="mini" placeholder="最多16个字" class="el-input-title" v-model.trim="ruleForm.sessionForm.formName" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input size="mini" class="el-input-title" v-model.trim="ruleForm.sessionForm.description"></el-input>
        </el-form-item>
        <el-form-item label="引导文案" prop="leadText">
          <el-input size="mini"  placeholder="最多50个字" class="el-input-title" type="textarea" v-model.trim="ruleForm.sessionForm.leadText" maxlength="50"></el-input>
        </el-form-item>
        <div @click="addCustomize" class="addCustomize el-icon-plus">自定义字段（至多6个）</div>
        <el-form-item v-for="(domain, index) in ruleForm.sessionForm.form">
          <el-row :gutter="40">
            <el-col :span="16">
              <el-input placeholder="请输入自定义字段名称（不超过10个字）" size="mini" class="el-input-title" v-model.trim="domain.placeholder" maxlength="10"></el-input>
            </el-col>
            <el-col :span="4">
              <el-checkbox label="必填" v-model="domain.required"></el-checkbox>
            </el-col>
            <el-col :span="4">
              <span @click="delCustomize(index)" class="iconfont icon-shanchu" ></span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="btn_box">
          <el-button type="primary" class="primary_btn" @click.stop="saveRuleForm">{{$t('public.confirm')}}</el-button>
          <el-button class="primary_btn" @click.stop="dialogHide">{{$t('public.cancel')}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import {deepClone} from '@/utils/m7Utils'
export default{
  name: "webchatSessionForm",
  data () {
    return {
      showAddDialog: false,
      tableData: [],
      ruleForm: {
        sessionForm: {
          formName: "",
          description: "",
          leadText: "",
          form: []
        }
      },
      initName: '',
      query: '',
      rules: {
        formName: [
          { required: true, message: '请填写表单名称', trigger: 'blur' },
        ],
        leadText: [
          { required: true, message: '请填写引导文案', trigger: 'blur' }
        ]}
    }
  },
  methods: {
    getFormList () {   // 获取表单列表
      var data = {
        page: 1,
        limit: 10
      }
      this.$store.dispatch('querySessionForm', data).then((resp) => {
        if (resp && resp.success) {
          var resData = deepClone(resp.list)
          resData.forEach((item, index) => {
            try {
              item.sessionForm = JSON.parse(item.sessionForm)
            } catch (a) {}
          })
          this.tableData = deepClone(resData)
        } else {
          this.tableData = []
        }
      })
    },
    addFormData () {   // 添加表单
      if (this.tableData.length >= 10) {
        this.$message.error('最多添加10个表单消息')
        return
      }
      this.ruleForm = {
        sessionForm: {
          formName: "",
          description: "",
          leadText: "",
          form: []
        }
      }
      this.showAddDialog = true
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields()
      }
    },
    dialogHide () {
      if (this.$refs['ruleForm']) {
        this.$refs['ruleForm'].resetFields()
      }
      this.ruleForm = {
        sessionForm: {
          formName: "",
          description: "",
          leadText: "",
          form: []
        }
      }
      this.showAddDialog = false
    },
    editForm (data, index) {   // 编辑表单
      this.showAddDialog = true
      this.ruleForm = deepClone(data)
      this.initName = this.ruleForm.sessionForm.formName
    },
    delForm (data) {    // 删除表单
      this.$confirm("确定要删除表单吗", this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          var sendForm = {
            _id: data._id
          }
          this.$store.dispatch("deleteSessionForm", sendForm).then((resp) => {
            if (resp && resp.success) {
              this.$message.success('删除成功')
              this.showAddDialog = false
              this.getFormList()
            } else {
              this.$message.error('保存失败')
            }
          })
        }).catch(() => {
        })
    },
    saveRuleForm () {   // 保存表单更改
      const arr = this.tableData
      const name = this.ruleForm.sessionForm.formName
      let isRepeart = arr.find((item, index) => {
        return name === item.sessionForm.formName
      })
      if (isRepeart && this.initName !== name) {
        this.$message.error('已存在同名称的表单')
        return
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!this.ruleForm.sessionForm.form.length) {
            this.$message.error('请至少添加一项自定义字段')
            return
          }
          if (this.ruleForm.sessionForm.formName.indexOf("&") !== -1 || this.ruleForm.sessionForm.formName.indexOf("%") !== -1) {
            this.$message.error('表单名称不可包含 & 或 % 等特殊符号')
            return
          }
          if (this.ruleForm.sessionForm.description.indexOf("&") !== -1 || this.ruleForm.sessionForm.description.indexOf("%") !== -1) {
            this.$message.error('描述不可包含 & 或 % 等特殊符号')
            return
          }
          if (this.ruleForm.sessionForm.leadText.indexOf("&") !== -1 || this.ruleForm.sessionForm.leadText.indexOf("%") !== -1) {
            this.$message.error('引导文案不可包含 & 或 % 等特殊符号')
            return
          }
          var formFlag = false
          var indexFlag = false
          this.ruleForm.sessionForm.form.forEach((item, index) => {
            if (!item.placeholder) {
              formFlag = true
            }
            if (item.placeholder && (item.placeholder.indexOf("&") !== -1 || item.placeholder.indexOf("%") !== -1)) {
              indexFlag = true
            }
          })
          if (formFlag) {
            this.$message.error('自定义字段名称不能为空')
            return
          }
          if (indexFlag) {
            this.$message.error('自定义字段名称不可包含 % 或 & 等特殊符号')
            return
          }
          
          var sendForm = deepClone(this.ruleForm)
          sendForm.sessionForm = JSON.stringify(this.ruleForm.sessionForm)
          var action = "addSessionForm"
          if (sendForm._id) {
            action = "editSessionForm"
          }
          this.$store.dispatch(action, sendForm).then((resp) => {
            if (resp && resp.success) {
              this.initName = ''
              this.$message.success('保存成功')
              this.showAddDialog = false
              this.getFormList()
            } else {
              this.$message.error('保存失败')
            }
          })
        } else {
          return false;
        }
      });
    },
    addCustomize () { // 添加自定义字段
      if (this.ruleForm.sessionForm.form.length < 6) {
        this.ruleForm.sessionForm.form.push({placeholder: '', type: 'input', required: false})
      }
    },
    delCustomize (index) { // 删除自定义字段
      this.ruleForm.sessionForm.form.splice(index, 1)
    }
  },
  beforeMount () {
    this.getFormList()
  }
}
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .webchatFormBox.box_height
    height calc(100% - 104px)
    box-sizing border-box
    display: flex;
    -ms-flex-direction column
    flex-direction column
    overflow-y auto
    font-size 12px
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
      margin-right 20px
    .wapper
      display flex
      flex-direction column
    .tool
      position relative
      border 1px solid #e7e7eb
      border-bottom 0
      padding  12px 15px
      /*display flex*/
      justify-content space-between
    .primary_btn
      padding 0px 10px
      min-width 70px
    .del
      color $c-pink
    .oper
      color #FF6B6B
    .modifyWebStatus
      padding 20px
      font-size 12px
      box-sizing border-box
      .modifyWebStatus__input
        margin-bottom 20px
  .addCustomize
    cursor pointer
    color $c-main
    margin 20px 0
  .icon-shanchu
    cursor pointer
    color $c-pink
  .btn_box
    .primary_btn
      float right
      margin-left 10px
</style>